//Made By LWP & SJQ

class TMapWX {
	constructor(key) {
		this.key = key;
	}
	
	getWXLocation(type, success, fail, complete) {
		type = type || 'gcj02';
		success = success || function () {
		};
		fail = fail || function () {
		};
		complete = complete || function () {
		};
		wx.getLocation({
			type,
			success: res => {
				wx.request({
					url: 'https://apis.map.qq.com/ws/geocoder/v1/',
					method: "get",
					data: {
						key: this.key,
						location: res["latitude"] + ',' + res["longitude"],
						get_poi: "1"
					},
					fail,
					success
				})
			}
			, fail, complete
		});
	}
	
	weather({success, fail, city}) {
		let type = 'gcj02';
		
		fail = fail || (e => console.log(e));
		
		let locationsuccess = ({data}) => {
			let city = data.result.address_component.city;
			this.cityGot({
				city, fail,
				success: ({data}) => {
					let cityDetail = undefined;
					for (const prop in data) {
						cityDetail = data[prop].split(',')
					}
					this.weatherGot({
						province: cityDetail[0],
						city: cityDetail[1],
						fail, success
					});
				}
			});
		}
		
		if (city) {
			this.cityGot({
				city, fail,
				success: ({data}) => {
					let cityDetail = undefined;
					for (const prop in data) {
						cityDetail = data[prop].split(',')
					}
					if (!cityDetail) {
						fail("城市不存在");
						return;
					}
					this.weatherGot({
						province: cityDetail[0],
						city: cityDetail[1],
						fail, success
					});
				}
			});
			return;
		}
		
		this.getWXLocation(type, locationsuccess);
	}
	
	cityGot({city, success, fail}) {
		let data = {
			city, source: "pc"
		}
		wx.request({
			url: 'https://wis.qq.com/city/like',
			method: 'GET',
			data,
			fail,
			success: ({data}) => {
				success(data);
			}
		})
	}
	
	weatherGot({province, city, success, fail}) {
		let data = {
			source: "pc",
			weather_type: 'observe|forecast_1h|forecast_24h|index|alarm|limit|tips|air|rise',
			province, city,
		}
		
		wx.request({
			url: 'https://wis.qq.com/weather/common',
			method: 'GET',
			data,
			fail,
			success: ({data}) => {
				data.data.city = city;
				data.data.province = province;
				success(data);
			}
		})
	}
}

module.exports.TMapWX = TMapWX;

//Made By LWP & SJQ